package com.bgybmi.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bgybmi.common.Constants;
import com.bgybmi.entity.Users;
import com.bgybmi.util.JsTikcetCon;
import com.bgybmi.util.RescouceReader;
import com.bgybmi.util.Utility;
import com.jfinal.core.Controller;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.qyweixin.sdk.api.ApiConfigKit;
import com.jfinal.qyweixin.sdk.api.ApiResult;
import com.jfinal.qyweixin.sdk.api.ConUserApi;
import com.jfinal.qyweixin.sdk.api.JsTicketApi;
import com.jfinal.qyweixin.sdk.api.LoginApi;
import com.jfinal.qyweixin.sdk.api.OAuthApi;
import com.jfinal.qyweixin.sdk.api.SendMessageApi;
import com.jfinal.qyweixin.sdk.api.JsTicketApi.JsApiType;
import com.jfinal.qyweixin.sdk.jfinal.MsgController;
import com.jfinal.qyweixin.sdk.msg.in.InMsg;
import com.jfinal.qyweixin.sdk.msg.send.QiYeTextMsg;
import com.jfinal.qyweixin.sdk.msg.send.Text;

/**
 * @author hecore 
 * <br>酒不醉人人自醉  
 * <br>一曲潇鸣断寸肠
 */
public class BaseController extends Controller {
    
	private static final Log log =  Log.getLog(MsgController.class);
	
	private String inMsgXml = null;		// 本次请求 xml数据	
	
	private InMsg inMsg = null;			// 本次请求 xml 解析后的 InMsg 对象
	
	protected String message = "";

	protected String redirectionUrl = RescouceReader.getProperties("config").getString("redirectonUrl");

	protected String UUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	protected boolean empty(Object o) {
		return Utility.empty(o);
	}

	/**
	 * 获得当前Request真实的IP地址
	 */
	protected String getIpAddress() {
		HttpServletRequest request = getRequest();

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 程序入口1  转向 index方法
	 */
	public void oath(){
		String user=getSessionAttr("loginuser");
		if(Utility.empty(user)){
			String url = "http://" + getRequest().getServerName()+"/meet";
			System.out.println("程序的专项"+url);
			String redirect_uri = null;
			String codeUrl = null;
			try {
				redirect_uri = URLEncoder.encode(url, "utf-8");
				System.out.println(redirect_uri);
				codeUrl = OAuthApi.getCodeUrl(redirect_uri,PropKit.get("corpId"));
				redirect(codeUrl);//重定向
				//getResponse().sendRedirect(codeUrl);//路径跳转，之后会带上相应的参数
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		}else{
			jspAttr();
			render("index.jsp");
		}
	}
	
	
	public String getOathUrl(String url){
		String redirect_uri = null;
		String codeUrl = null;
		try {
			redirect_uri = URLEncoder.encode(url, "utf-8");
			System.out.println(redirect_uri);
			codeUrl = OAuthApi.getCodeUrl(redirect_uri,PropKit.get("corpId"));
			//redirect(codeUrl);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println(codeUrl);
		return codeUrl;
	}
	
	/**
	 * https://qyapi.weixin.qq.com/cgi-bin/service/get_login_info?access_token=ACCESS_TOKEN
	 */
	public void logmsg(){
		//获取用户的接口
		System.out.println("接口调用");
		String baseurl="ttps://qyapi.weixin.qq.com/cgi-bin/service/get_login_info";
		ApiResult userInfoApiResult=LoginApi.getUserInfo();
		if (userInfoApiResult.isSucceed()) {
			String userInfoJson=userInfoApiResult.getJson();
			System.out.println("调用结果"+userInfoJson);
			JSONObject object = JSON.parseObject(userInfoJson);
			
		}
	}
	
	/**
	 * 获得未被XSS过滤器处理过的原始参数值
	 */
	protected String getOriginalParameter(String name) {
		HttpServletRequest request = getRequest();
		ServletRequest r = request;
		while (r instanceof HttpServletRequestWrapper) {
			r = ((HttpServletRequestWrapper) r).getRequest();
		}
		return r.getParameter(name);
	}

	/**
	 * 按照名称获得Cookie中存储的值
	 */
	protected String getCookieValue(String name) {
		HttpServletRequest request = getRequest();
		Cookie[] cookies = request.getCookies();
		String value = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (name.equals(cookie.getName())) {
					value = cookie.getValue();
					break;
				}
			}
		}
		return value;
	}
    
	protected void GobalUser(){
		String user=getSessionAttr(Constants.loginuser);
		System.out.println("全局的用户"+user);
	}
	/**
	 * 用户为空先转发一次
	 * 然后返回来用户
	 */
	protected void saveUser(){
		String user=getSessionAttr("loginuser");
		System.out.println("拦截中的"+user);
        if(Utility.empty(user)){
    		if (isParaBlank("code")) {
    			System.out.println("程序没有code");
            	oAuthRedirect(); //转发    跳转之后又发生了,return 这样会报错
    		}
        	user=setOathCode();
        	if(!Utility.empty(user)){
            	System.out.println("我们拿到了用户"+user);
            	setSessionAttr("loginuser",user);
        	}
        }
        // return user;
	}
	//Cookie cookie = new Cookie("loginUser",user); // 新建Cookie
	//cookie.setMaxAge(Integer.MAX_VALUE); // 设置生命周期为MAX_VALUE      
    //setCookie("loginuser",user,Integer.MAX_VALUE);   
	
	protected void jspAttr(){   	
		saveUser();		
		String user=getSessionAttr("loginuser");
		setAttr("loginuser",user);
	}
	
	/**
	 * @return    redirect_uri?code=CODE&state=STATE
	 * @throws IOException 
	 */
	public void oAuthRedirect(){
		String url = "http://" + getRequest().getServerName() + getRequest().getContextPath();
		if(url.contains(".jsp")){
			url="http://" + getRequest().getServerName();
		}
		String redirect_uri = null;
		String codeUrl = null;
		try {
			redirect_uri = URLEncoder.encode(url, "utf-8");
			codeUrl = OAuthApi.getCodeUrl(redirect_uri,PropKit.get("corpId"));
			//PC测试
			redirect(codeUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 授权处理
	 */
	
	
	/**
	 * 判断当前访问设备是否是手机
	 */
	protected boolean isPhone() {
		HttpServletRequest request = getRequest();
		String agent = request.getHeader("user-agent");
		if (agent != null) {
			agent = agent.toLowerCase();
			return agent.indexOf("iphone") != -1 || agent.indexOf("android") != -1;
		} else
			return false;
	}
    
	/**
	 * This function is send to wechat to confrom our url is legal.
	 */
	public void JsVerify() {
		// TODO Auto-generated method stub
		String jsapi_ticket=JsTicketApi.getTicket(JsApiType.jsapi).getTicket();
				//JsTicketApi.getTicket(JsApiType.jsapi);
				//JsTikcetCon.getInstance().getAccessTokenAndJsapiTicket();		
		String nonce_str = create_nonce_str();
		// 注意 URL 一定要动态获取，不能 hardcode.
		String url = "http://" + getRequest().getServerName() // 服务器地址
				// + ":"
				// + getRequest().getServerPort() //端口号
				+ getRequest().getContextPath() // 项目名称
				+ getRequest().getServletPath();// 请求页面或其他地址
		String qs = getRequest().getQueryString(); // 参数
		if (qs != null) {
			url = url + "?" + (getRequest().getQueryString());
		}
		System.out.println("url>>>>" + url);
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket +
        "&noncestr=" + nonce_str +
        "&timestamp=" + timestamp +
        "&url=" + url;
		String signature = HashKit.sha1(str);
		System.out.println("corpId " + ApiConfigKit.getApiConfig().getCorpId()
				+ "  nonceStr " + nonce_str + " timestamp " + timestamp);
		System.out.println("url " + url + " signature " + signature);
		System.out.println("nonceStr " + nonce_str + " timestamp " + timestamp);
		System.out.println(" jsapi_ticket " + jsapi_ticket);
		System.out.println("nonce_str  " + nonce_str);
		setAttr("appId", ApiConfigKit.getApiConfig().getCorpId());
		setAttr("nonceStr", nonce_str);
		setAttr("timestamp", timestamp);
		setAttr("url", url);
		setAttr("signature", signature);
		setAttr("jsapi_ticket", jsapi_ticket);
	}
	
	public void JsVerify(String agentId) {
		// TODO Auto-generated method stub
		String jsapi_ticket=JsTicketApi.getTicket(JsApiType.jsapi).getTicket();
				//JsTicketApi.getTicket(JsApiType.jsapi);
				//JsTikcetCon.getInstance().getAccessTokenAndJsapiTicket();		
		String nonce_str = create_nonce_str();
		// 注意 URL 一定要动态获取，不能 hardcode.
		String url = "http://" + getRequest().getServerName() // 服务器地址
				// + ":"
				// + getRequest().getServerPort() //端口号
				+ getRequest().getContextPath() // 项目名称
				+ getRequest().getServletPath();// 请求页面或其他地址
		String qs = getRequest().getQueryString(); // 参数
		if (qs != null) {
			url = url + "?" + (getRequest().getQueryString());
		}
		System.out.println("url>>>>" + url);
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket +
        "&noncestr=" + nonce_str +
        "&timestamp=" + timestamp +
        "&url=" + url;
		String signature = HashKit.sha1(str);
		System.out.println("corpId " + ApiConfigKit.getApiConfig(agentId).getCorpId()
				+ "  nonceStr " + nonce_str + " timestamp " + timestamp);
		System.out.println("url " + url + " signature " + signature);
		System.out.println("nonceStr " + nonce_str + " timestamp " + timestamp);
		System.out.println(" jsapi_ticket " + jsapi_ticket);
		System.out.println("nonce_str  " + nonce_str);
		setAttr("appId",  ApiConfigKit.getApiConfig(agentId).getCorpId());
		setAttr("nonceStr", nonce_str);
		setAttr("timestamp", timestamp);
		setAttr("url", url);
		setAttr("signature", signature);
		setAttr("jsapi_ticket", jsapi_ticket);
	}
	
	public void JsJson(){
		String jsapi_ticket=JsTikcetCon.getInstance().getAccessTokenAndJsapiTicket();		
		String nonce_str = create_nonce_str();
		// 注意 URL 一定要动态获取，不能 hardcode.
		String url = "http://" + getRequest().getServerName() // 服务器地址
				// + ":"
				// + getRequest().getServerPort() //端口号
				+ getRequest().getContextPath() // 项目名称
				+ getRequest().getServletPath();// 请求页面或其他地址
		String qs = getRequest().getQueryString(); // 参数
		if (qs != null) {
			url = url + "?" + (getRequest().getQueryString());
		}
		System.out.println("url>>>>" + url);
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket +
        "&noncestr=" + nonce_str +
        "&timestamp=" + timestamp +
        "&url=" + url;
		String signature = HashKit.sha1(str);
		Map every=new HashMap();
		every.put("appId",ApiConfigKit.getApiConfig().getCorpId());
		every.put("nonceStr", nonce_str);
		every.put("timestamp", timestamp);
		every.put("url", url);
		every.put("signature", signature);
		every.put("jsapi_ticket", jsapi_ticket);
		renderJson(every);
	}
	
	public void JsUrlJson(){
		String url=getPara("url");
		String jsapi_ticket=JsTikcetCon.getInstance().getAccessTokenAndJsapiTicket();		
		String nonce_str = create_nonce_str();
		// 注意 URL 一定要动态获取，不能 hardcode
		System.out.println("url>>>>" + url);
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket +
        "&noncestr=" + nonce_str +
        "&timestamp=" + timestamp +
        "&url=" + url;
		String signature = HashKit.sha1(str);
		Map every=new HashMap();
		every.put("appId",ApiConfigKit.getApiConfig().getCorpId());
		every.put("nonceStr", nonce_str);
		every.put("timestamp", timestamp);
		every.put("url", url);
		every.put("signature", signature);
		every.put("jsapi_ticket", jsapi_ticket);
		renderJson(every);
	}
	
	//common function style
	public static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
      
	protected static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}
	
	/**
	 * 外界的转向
	 * 2017-12-18 优化了显示速度，没必要每次都查询
	 */
	public void getOathUrl(){
		//获取验证Url,然后转向。
		//OAuthApi.getAuthorizeURL();
		String subUrl=getPara("subUrl");
		//subUrl="repair/mybx";
		System.out.println(subUrl);
		switch (subUrl) {
		case "hyxq":
			subUrl=BxEnum.hyxq.getMenu();
			break;
		case "myhy":
			subUrl=BxEnum.myhy.getMenu();	
			break;
		case "bxxq":
			subUrl=BxEnum.bxxq.getMenu();
			break;
		case "bxsq":
			subUrl=BxEnum.bxsq.getMenu();
			break;
		case "mybx":
			subUrl=BxEnum.mybx.getMenu();
			break;
		case "meetinfo":
			String xh=getPara("xh");
			subUrl=BxEnum.meetinfo.getMenu()+"?xh="+xh;
			break;
		case "bxinfo":
			String id=getPara("id");
			subUrl=BxEnum.bxinfo.getMenu()+"?id="+id;
			break;
		default:
			break;
		}
		Cookie cookie=new Cookie("JSEESIONID",getSession().getId());
		cookie.setMaxAge(1800);
		cookie.setPath("/");
		getResponse().addCookie(cookie);
		String redirectUrl="";
		String codeUrl="";
		String url = "http://" + getRequest().getServerName() // 服务器地址
				+ getRequest().getContextPath();// 项目名称
		redirectUrl=url+"/"+subUrl;	
		codeUrl=redirectUrl;
		if(Utility.empty(getSessionAttr("loginuser"))){
			codeUrl=OAuthApi.getAuthorizeURL(redirectUrl,ApiConfigKit.getApiConfig().getCorpId(),"1",ApiConfigKit.getApiConfig().getAgentId(),false);
		}
		System.out.println("跳转的路径"+codeUrl);
		redirect(codeUrl);
	}
	
	public void userSyn(String userid){
		Users u=new Users();
		List<Users> fbu = u.findByUsername(userid);
		if(fbu.size()==0&&null!=userid){
			ApiResult apiResult = ConUserApi.getUser(userid);	
			System.out.println(apiResult.getJson());
			u.set("loginname",userid);
			u.set("username", apiResult.get("name"));
			u.set("mobile", apiResult.get("mobile"));
			u.set("avatar",apiResult.get("avatar"));
			u.set("gender",apiResult.get("gender"));
			u.set("groupid",apiResult.get("department"));
			u.save();
		}
	}
	
	/**
	 * @description  if user in our company then userid,else openid
	 * @return 
	 */
	protected String setOathCode(){
		String userId =null;
		String openid=null;	
		String deviceId=null;
		///?code=BQE8QoOMgc9m5fwjKUIFgc4HuSSI8deJcFGWRvWuD3E&state=1
		if (!isParaBlank("code")) {
			String code = getPara("code");					
			ApiResult userInfoApiResult = OAuthApi.getUserInfoByCode(code);
			if (userInfoApiResult.isSucceed()) {
				String userInfoJson=userInfoApiResult.getJson();
				JSONObject object = JSON.parseObject(userInfoJson);
				deviceId = object.getString("DeviceId");
				try {
					userId = object.getString("UserId"); //如果获取userId为空 说明没有关注					
					if (userId!=null && !userId.equals("")) {
						ApiResult toOpenIdApiResult = OAuthApi.ToOpenId("{\"userid\":\""+userId+"\",\"agentid\":0}");
						if (toOpenIdApiResult.isSucceed()) {
							openid=JSON.parseObject(toOpenIdApiResult.getJson()).getString("openid");
						}
					}else {
						openid = object.getString("OpenId");
						String json="{\"openid\":\""+openid+"\"}"; //如果未关注 openid无法转化为userid						
						ApiResult toUserIdApiResult = OAuthApi.ToUserId(json);
						if (toUserIdApiResult.isSucceed()) {
							userId=JSON.parseObject(toUserIdApiResult.getJson()).getString("userid");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}			
			System.out.println("得到的openid"+ "userId:"+userId+" deviceId:"+deviceId+" openid:"+openid);
			setAttr("openID", "userId:"+userId+" deviceId:"+deviceId+" openid:"+openid);	
			userSyn(userId);
		}
		//用户的openid 是不是可以存储起来以后一直使用，这样用户只关注一次就可以了。
		return userId;
	}	
	
	/**
	 * 获取用户信息
	 * @param userid
	 * @return
	 */
	public String getUserInfo(String userid){
		ApiResult apiResult = ConUserApi.getUser(userid);
		return apiResult.getJson();
	}
	//免登配置--->系統如何實現微信直接登錄然後記錄用戶的信息呢-->攔截信息，然後注入用戶
	
	/**
	 * @ user  a,b,c-->a|b|c
	 * 发送文本消息 未成功
	 * {
		   "touser": "UserID1|UserID2|UserID3",
		   "toparty": " PartyID1 | PartyID2 ",
		   "totag": " TagID1 | TagID2 ",
		   "msgtype": "text",
		   "agentid": 1,
		   "text": {
		       "content": "Holiday Request For Pony(http://xxxxx)"
		   },
		   "safe":0
		}
	 */
	public void sendTextMssage(String user,String msg) {
		QiYeTextMsg text = new QiYeTextMsg();
		text.setAgentid(PropKit.get("agentId"));
		text.setText(new Text(msg)); //发送的信息
		text.setSafe("0");      //是否直接显示该链接 安全消息
		text.setTouser(user); //发送的用户
		//发送信息的终端用户
		ApiResult sendTextMsg = SendMessageApi.sendTextMsg(text);
		sendTextMsg.getJson();
	}
	
	public void userIdToName(){
		String userid=getPara("userid");
		setAttr("res", changeUser(userid));
		renderJson();
	}
	
	public String changeUser(String user){
		String restr=null;
		List<Users> fbu = Users.me.findByUsername(user);
		if (fbu.isEmpty()) {
			restr=user;
		}else{
			restr=fbu.get(0).get("username");
		}
		return restr;
	}
	
	public void getUser(){
		String userid=getSessionAttr("loginuser");
		Users user= Users.me.findUserByUsername(userid);
		renderJson(user);
	}
}